package jsp;

import entity.User;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.*;
import java.util.Random;

/**
 * @author 黄衡熙
 * @version 1.0
 */
@WebServlet("*.code")
public class codeServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws SecurityException, IOException, ServletException {
        String path = req.getServletPath();
        switch (path) {
            case "/show.code":
                showCode(req, resp);
                break;
            case "/login.code":
                login(req,resp);
                break;
            case "/logout.code":
                logout(req, resp);
                break;
        }
    }
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 清除session中的数据
        req.getSession().invalidate();
//        重定向
        resp.sendRedirect(req.getContextPath()+"/jsp/main2.jsp");
    }
    protected void showCode(HttpServletRequest req,HttpServletResponse resp) throws SecurityException,IOException{
//在内存中定义一个画板
        BufferedImage image=new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB);
// 获取画笔
        Graphics graphics=image.getGraphics();
//        指定画笔搜填充的矩形区域
        graphics.fillRect(0,0,50,25);
//        设置一个随机颜色填充矩形区域
        Random random=new Random();
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
//        设置字体
        graphics.setFont(new Font(("宋体"),Font.BOLD+Font.ITALIC,18));
        // 生成验证码内容,要求随机4位英文字母或者数字
        // 指定一个字符串,该字符串中包含验证码中一切可能出现的字符
        // 获取随机索引位置的字符
        String s = "0123456789qwertyuipolkjhgfdsazxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        String code = buffer.toString();

        // 生成验证码之后,将其数据保存到session,便于校验
        req.getSession().setAttribute("code", code);
        System.out.println("验证码:" + code);

        // 将生成的随机字符串填充到画板中
        graphics.drawString(code, 5, 18);
        // 生成图片
        ImageIO.write(image, "JPEG", resp.getOutputStream());

    }
    protected void login(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String image = (String) req.getSession().getAttribute("code");
        if(!image.equals(code)){
            req.setAttribute("loginMsg","验证码不正确");
            req.getRequestDispatcher("/jsp/login.jsp").forward(req,resp);
        }else{
            Connection conn=null;
            PreparedStatement ps=null;
            ResultSet rs=null;
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","qq670892");
                String sql="select username,password from t_users where username=? and password=?";
                ps=conn.prepareStatement(sql);
                ps.setString(1,username);
                ps.setString(2,password);
                rs=ps.executeQuery();
                if(rs.next()){
                User user=new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                    // 登录成功之后,将查询到的用户信息保存到session中
//                     req.getSession()如果当前用户已有 Session（如之前访问过网站），则返回已存在的 Session；
//                    setAttribute第一个参数 "user" 是键（key）,第二个参数 user 是值（value）
                    req.getSession().setAttribute("user",user);
                    // 登录成功之后,一般表示当前用户相关功能块结束了,进入下一个功能块
                    // 对于这种场景,一般使用重定向
                    resp.sendRedirect(req.getContextPath()+"/jsp/main2.jsp");
                    return;
                }
                // 如果没有进入分支,说明没有查询到结果,即:用户名或密码错误
                // 返回错误信息
                req.setAttribute("loginMsg","用户名或密码错误");
//                转发
                req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("注册驱动异常");
            } catch (SQLException e) {
                throw new RuntimeException("获取连接异常");
            }finally {
                if(conn !=null){
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        throw new RuntimeException("释放资源异常");
                    }
                }if(ps !=null){
                    try {
                        ps.close();
                    } catch (SQLException e) {
                        throw new RuntimeException("释放资源异常");
                    }
                }if(rs !=null){
                    try {
                        rs.close();
                    } catch (SQLException e) {
                        throw new RuntimeException("释放资源异常");
                    }
                }
            }
        }

    }
}
